package com.example.petadopt.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.dao.UserDao;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.entity.User;
import com.example.petadopt.utils.CurrentUserUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private ImageView ivTogglePassword;
    private CheckBox cbAdminLogin;

    private boolean isPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        importPetData();
        initView();
        initListener();

        XXPermissions.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.READ_MEDIA_IMAGES)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                    }
                });
    }

    /**
     * 从assets导入宠物数据
     */
    private void importPetData() {
        if (PetDao.getPetCount() > 0) {
            // 如果数据库中已有数据，则不进行导入
            return;
        }
        try {
            // 打开JSON文件
            InputStream inputStream = getAssets().open("pet.json");
            // 从JSON加载宠物数据
            Result<List<Pet>> result = PetDao.loadPetsFromAssets(inputStream);

            if (result.isSuccess() && result.getData() != null) {
                List<Pet> petList = result.getData();
                // 将宠物数据导入到数据库
                Result<Void> importResult = PetDao.importPetsFromJson(petList);
                if (!importResult.isSuccess()) {
                    Toast.makeText(this, importResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "导入数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);
        ivTogglePassword = findViewById(R.id.iv_toggle_password);
        cbAdminLogin = findViewById(R.id.cb_admin_login);
    }

    private void initListener() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                if (username.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 判断是否是管理员登录
                if (cbAdminLogin.isChecked()) {
                    // 管理员登录验证
                    if ("admin".equals(username) && "admin".equals(password)) {
                        Toast.makeText(LoginActivity.this, "管理员登录成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, "管理员用户名或密码错误", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 普通用户登录验证
                    Result<User> loginResult = UserDao.login(username, password);
                    if (loginResult.isSuccess()) {
                        // 登录成功，保存当前用户ID
                        User user = loginResult.getData();
                        CurrentUserUtils.setCurrentUser(user.getId());

                        Toast.makeText(LoginActivity.this, loginResult.getMessage(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // 登录失败
                        Toast.makeText(LoginActivity.this, loginResult.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        ivTogglePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePasswordVisibility();
            }
        });

        cbAdminLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbAdminLogin.isChecked()) {
                    // 提示管理员登录信息
                    Toast.makeText(LoginActivity.this, "请使用管理员账户登录", Toast.LENGTH_SHORT).show();
                    etUsername.setHint("管理员用户名");
                    etPassword.setHint("管理员密码");
                } else {
                    // 恢复普通提示
                    etUsername.setHint("请输入用户名");
                    etPassword.setHint("请输入密码");
                }
            }
        });
    }

    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            ivTogglePassword.setImageResource(R.drawable.ic_password_hide); // 设置为不可见图标
        } else {
            // 显示密码
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            ivTogglePassword.setImageResource(R.drawable.ic_password_show); // 设置为可见图标
        }
        isPasswordVisible = !isPasswordVisible;

        // 将光标移到文本末尾
        etPassword.setSelection(etPassword.getText().length());
    }
} 